﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using DataTransferObject;
using Presentation.Infrastructure;

namespace Presentation
{
    public class DashboardViewModel : ViewModelBase
    {
        private bool _isLoading;
        private readonly ObservableCollection<SignalementDTO> _signalementsCollection;

        private readonly SimpleCommand _signalerPanneCommand;

        public ObservableCollection<SignalementDTO> SignalementsCollection
        {
            get { return _signalementsCollection; }
        }

        public SimpleCommand SignalerPanneCommand
        {
            get { return _signalerPanneCommand; }
        }

        public bool IsLoading
        {
            get { return _isLoading; }
            set
            {
                _isLoading = value;
                this.NotifyPropertyChanged(o => o.IsLoading);
                RefreshCommands();
            }
        }

        public DashboardViewModel()
        {
            Title = "Signalements en cours";
            CurrentUser = ProxyClient.CurrentUser;

            _signalementsCollection = new ObservableCollection<SignalementDTO> ();
            _signalerPanneCommand = new SimpleCommand(OnSignalerPanneCommandExecuted, OnSignalerPanneCommandCanExecute);
            RefreshSignalements();
        }

        public void RefreshSignalements()
        {
            LoadSignalementsAsync();
        }

        private void LoadSignalementsAsync()
        {
            IsLoading = true;

            ProxyClient.Client.GetPendingSignalementsCompleted += (sender, args) =>
            {
                var pendingSignalements = args.Result;
                if (pendingSignalements != null)
                {
                    _signalementsCollection.Clear();
                    _signalementsCollection.AddRangeAsync(pendingSignalements.OrderByDescending(o => o.BeginDate));
                }
                IsLoading = false;
            };

            ProxyClient.Client.GetPendingSignalementsAsync(); 
        }

        protected override void RefreshCommands()
        {
            _signalerPanneCommand.RaiseCanExecuteChanged();
        }

        private bool OnSignalerPanneCommandCanExecute(object param)
        {
            return !IsLoading;
        }

        private void OnSignalerPanneCommandExecuted(object param)
        {
            NavigationService.Instance.NavigateTo(typeof(ReportPanneView));
        }
    }
}
